import pickle

class Package():
    
    #hash_alg = "md5"
    #hashing = False

    def __init__(self,command):
        self.command = command
        self.valido = True
        self.keys = {}
        
    def add(self,key,value):
        self.keys[key] = value
        
    def get(self,key):
        try: value = self.keys[key]
        except KeyError:
            value = ""
        return value
    
    def fromStr(self,string):
        
        #if(Paquete.hashing):
            #hash_size = hashlib.new(Paquete.hash_alg).digest_size *2
            #hash = string[0:hash_size]
        
            #string = str[hash_size:len(string)]
       
            #hash2 = hashlib.new(Paquete.hash_alg)
            #hash2.update(string)
            #hash2 = hash2.hexdigest()
            
            #if  hash == hash2:
                #print "paq okaa"
            
        string = str(string)
        #print string
        command = (string[0:20]).strip()
        #print command
        pkg = Package(command)
        
        pos = 20
        while pos < len(string):
            key = string[pos:pos+20].strip()
            #print "key:" , key
            size = int(string[pos+20:pos+32])
            #print "size:" , size
            value = string[pos+32:pos+32+size]
            #print "value", value
            pkg.add(key,value)
            
            pos = pos+32+size
            
        #print "\n\n"
        return pkg
        
    
    
    def fromStr2(self,data):
        data = str(data)
        a = pickle.loads(data)
        return a
    fromStr = classmethod(fromStr2)
    
    def toStr(self):
        #command = self.command
        #while len(command) < 20:
        #    command = command + " "
            
        #pkgStr = command
        
        #for key, value in self.keys.iteritems():
        #    while len(key) < 20:
        #        key = key + " "
        #    size = str(len(value))
        #    while len(size) < 12:
        #        size = size + " "
            
        #    pkgStr = pkgStr + key + size + value
        
        #if Paquete.hashing:
            #hash = hashlib.new(Paquete.hash_alg)
            #hash.update(pkgStr)
            #hash = hash.hexdigest()
            #pkgStr = hash + pkgStr
            
        #return pkgStr
        a = pickle.dumps(self)
        print "len",len(a)
        return a
        
    #def toZstr(self):
    #    return zlib.compress(self.tostr(),9)
    #def fromZstr(self,string):
    #    return self.fromstr(zlib.decompress(string))
    #fromZStr = classmethod(fromZStr)
